import { defineStore } from 'pinia'

// 标签类型（与页面使用的结构保持一致）
export interface IndustryTag {
  id: number
  tagName: string
  status?: any
  createTime?: any
}

// 会议新闻项
export interface IndustryNewsItem {
  id: number
  title: string
  summary: string
  publishDate: string
  coverImageUrl: string
  content: string
  views?: number
  likes?: number
  collects?: number
  tags: IndustryTag[]
}

// 会议视频项
export interface IndustryVideoItem {
  id: number
  title: string
  summary: string
  durationMinutes: number
  publishDate: string
  coverImageUrl: string
  videoUrl: string
  views?: number
  likes?: number
  collects?: number
  tags: IndustryTag[]
}

// Pinia 缓存：避免详情页重复发起请求
export const useIndustryBeltStore = defineStore('industryBelt', {
  state: () => ({
    currentNews: null as IndustryNewsItem | null,
    currentVideo: null as IndustryVideoItem | null,
    newsById: {} as Record<number, IndustryNewsItem>,
    videosById: {} as Record<number, IndustryVideoItem>,
  }),

  // 启用持久化（依赖 pinia-plugin-persistedstate）
  persist: true,

  actions: {
    // 写入当前新闻并缓存
    setCurrentNews(item: IndustryNewsItem) {
      if (!item || typeof item.id !== 'number') return
      this.currentNews = item
      this.newsById[item.id] = item
    },

    // 写入当前视频并缓存
    setCurrentVideo(item: IndustryVideoItem) {
      if (!item || typeof item.id !== 'number') return
      this.currentVideo = item
      this.videosById[item.id] = item
    },

    // 批量缓存新闻列表
    cacheNewsList(list: IndustryNewsItem[]) {
      if (!Array.isArray(list)) return
      for (const n of list) {
        if (n && typeof n.id === 'number') {
          this.newsById[n.id] = n
        }
      }
    },

    // 批量缓存视频列表
    cacheVideoList(list: IndustryVideoItem[]) {
      if (!Array.isArray(list)) return
      for (const v of list) {
        if (v && typeof v.id === 'number') {
          this.videosById[v.id] = v
        }
      }
    },

    // 读取缓存项
    getNewsById(id: number) {
      return this.newsById[id] || null
    },
    getVideoById(id: number) {
      return this.videosById[id] || null
    },

    // 清空当前项或全部缓存
    clearCurrent() {
      this.currentNews = null
      this.currentVideo = null
    },
    clearAll() {
      this.currentNews = null
      this.currentVideo = null
      this.newsById = {}
      this.videosById = {}
    },
  },
})